 const cors = require("cors");
 const _ = require("lodash");
 const url = require("url");
 let router = require("express").Router();
 let mysqlPool = require("../mysql");

 router.all("*", cors({
     origin: function (origin, callback) {
         if (origin) {
             let parsed = url.parse(origin);
             if (parsed.hostname == "localhost" || parsed.hostname.includes("192.168")) {
                 callback(null, origin);
             } else {
                 callback(new Error)
             }
         } else {
             callback(null, "*")
         }
     }
 }), (req, res, next) => next());

 router.get("/full5000", (req, res) => {
     const limit_query = '\nWHERE test_part11_detail.test_id<=24001 AND test_part11_detail.row_id<=1000\n';
     let query_speed = new Promise((resolve, reject) => {
         mysqlPool.query(`SELECT
            test_part11.SNG_label AS sng,
                test_part11_detail.row_id,
                AVG(test_part11_detail.speed) AS v_avg,
                MAX(test_part11_detail.speed) AS v_max,
                MIN(test_part11_detail.speed) AS v_min
            FROM
                test_part11_detail
            INNER JOIN test_part11 ON
             test_part11.test_id = test_part11_detail.test_id` +
             limit_query +
             `GROUP BY
                test_part11.SNG_label,
                row_id;`,
             (err, results, fileds) => {
                 if (err) {
                     reject(err);
                 } else {
                     resolve(results);
                 }
             });
     });
     let query_range = new Promise((resolve, reject) => {
         mysqlPool.query(`select 
        MAX(test_part11_detail.speed) AS v_max,
        MIN(test_part11_detail.speed) AS v_min
        from test_part11_detail
        ` + limit_query, (err, results, fileds) => {
             if (err) return reject(err);
             else return resolve(results);
         })
     })

     Promise.all([query_speed, query_range]).then(([results, min_max]) => {
         // debugger
         //依赖sql的正确性,results应该是按照sng的一定顺序排好的
         let array = [];
         results.forEach((e, i, a) => {
             if (i == 0 || a[i - 1]['sng'] != e['sng']) {
                 array.push({
                     sng: e['sng'],
                     rows: [e]
                 })
             } else {
                 array[array.length - 1]['rows'].push(e);
             }
         });
         res.send({
             max: min_max[0]['v_max'],
             min: min_max[0]['v_min'],
             array,
         })
     })
 })
 /**
  * 
  * select test_part11_detail.row_id,AVG(test_part11_detail.speed),MAX(test_part11_detail.speed),MIN(speed) from test_part11_detail where test_part11_detail.test_id<4250 group by row_id;select test_part11_detail.row_id,AVG(test_part11_detail.speed),MAX(test_part11_detail.speed),MIN(speed) from test_part11_detail where test_part11_detail.test_id<4250 group by row_id;
  */
 /**
 SELECT
 test_part11.SNG_label AS sng,
 	test_part11_detail.row_id,
 	AVG(test_part11_detail.speed) AS v_avg,
 	MAX(test_part11_detail.speed) AS v_max,
 	MIN(test_part11_detail.speed) AS v_min
 FROM
 	test_part11_detail
 INNER JOIN test_part11 ON
  test_part11.test_id = test_part11_detail.test_id
 GROUP BY
 	test_part11.SNG_label,
 	row_id;
  */
 router.get("/foobar", function trend_foobar(req, res) {
     let query_speed = new Promise((resolve, reject) => {
         mysqlPool
             .query("select row_id,test_id,speed from test_part11_detail WHERE test_id<=4250 GROUP BY row_id, test_id",
                 (err, results, fileds) => {
                     if (err) {
                         reject(err);
                     } else {
                         resolve(results);
                     }
                 });
     });
     query_speed
         .then((results) => {

             let output_array = [];
             results.forEach((ele, idx, arr) => {
                 //基于SQL语句提供的合理保证:row_id,test_id是升序排列好的
                 if (idx == 0 || ele.row_id != arr[idx - 1].row_id) {
                     output_array.push({
                         row_id: ele.row_id,
                         speed: {
                             max: ele.speed,
                             min: ele.speed,
                             avg: ele.speed,
                         },
                         count_test_id: 1
                     })
                 } else {
                     let last = output_array[output_array.length - 1];
                     last.speed.max = (ele.speed > last.speed.max) ? ele.speed : last.speed.max;
                     last.speed.min = (ele.speed < last.speed.min) ? ele.speed : last.speed.min;
                     last.count_test_id++;
                     last.speed.avg = last.speed.avg + (ele.speed - last.speed.avg) / last.count_test_id;
                 }
             });
             let max_speed = _.maxBy(output_array, (e => e.speed.max)).speed.max
             let min_speed = _.minBy(output_array, e => e.speed.min).speed.min;
             res.send({
                 max_speed,
                 min_speed,
                 output_array,

             })
         })
         .catch((error) => {
             res.status(500);
             res.send({
                 error
             })
         })


 });


 module.exports = router;